import Toast from 'tdesign-miniprogram/toast/index';
import {
  bannerFormat, imgFormat
} from '../../utils/imgFormat';
import axios from '../../utils/axios';

Page({
  data: {
    imgSrcs: [],
    roomsList: [],
    pageLoading: false,
    current: 1,
    autoplay: true,
    duration: '500',
    interval: 5000,
    fabButton:{
      class:"ddda",
      style:{
        color:"red"
      }
    },
    navigation: {
      type: 'dots',
    },
    swiperImageProps: {
      mode: 'scaleToFill',
    },
    roomsListLoadStatus: 0,

    cityList: [],
    city: '',
    lat: '',
    lng:'',
    hasLocation: false,

    enable: false,
    loadingProps: {
      size: '50rpx',
    },
    backTopVisible: false,
  },

  goodListPagination: {
    index: 0,
    num: 20,
  },

  privateData: {
    tabIndex: 0,
  },
  toTuangou(){
    wx.navigateTo({
      url: '/pages/mt/mt',
    })
  },
  onCall(e){
    const {u = []} = e.currentTarget.dataset;
    if(u.length>0){
      wx.makePhoneCall({
        phoneNumber: u[0].phone,
      })
    }else{
      wx.makePhoneCall({
        phoneNumber: "15600595555",
      })
    }
  },
  onShow() {
    this.getTabBar().init();
  },

  onLoad() {
    this.checkLocationAuth();
    // this.init();
  },
  onRefresh() {
    this.setData({
      enable: true
    });
    this.init()
  },
  onScroll(e) {
    const { scrollTop } = e.detail;

    this.setData({
      backTopVisible: scrollTop > 100,
    });
  },
  getLocation(e) {
    const {u} = e.currentTarget.dataset
    wx.openLocation({
      latitude: u.lat,
      longitude: u.lng,
      scale: 18
    })
  },
  // 触底加载
  onReachBottom() {},

  // 下拉加载
  onPullDownRefresh() {},
  init() {
    this.getSwipers();
    this.loadHomePage();
  },
  onShareAppMessage(e) {},
  loadHomePage() {
    wx.showLoading({
      title: '加载中',
    });
    this.loadRoomsList(true);
  },
  gotToDetail(e) {
    const item = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: `/pages/shop-detail/detail?companyId=${item.ID}&distance=${item.distance}`,
    });
  },

  tabChangeHandle(e) {
    // this.privateData.tabIndex = e.detail;
    // this.loadRoomsList(true);
  },

  onReTry() {
    // this.loadRoomsList();
  },

  async getSwipers() {
    this.setData({
      pageLoading: true
    });
    const res = await axios.get('/app/getAdList');
    this.setData({
      pageLoading: false,
      imgSrcs: res?.data?.banners?.map((v) => bannerFormat(v.url))
    });
  },

  async getCityList() {
    this.setData({
      pageLoading: true
    });

    wx.getLocation({
      success: res => {
        const lat = res.latitude
        const lng = res.longitude
        axios.get('/app/cityList', {
          lat,
          lng
        }).then(res => {
          this.setData({
            pageLoading: false,
            cityList: res.data || [],
            city: res.city,
            lat,
            lng,
            hasLocation: true,
          });
          this.init()
        })
      },
      fail: (err) => {
        console.log(err)
      }
    })
  },

  toCitySelect() {
    wx.navigateTo({
      url: `/pages/select-location/select-location?cityList=${JSON.stringify(this.data.cityList)}&city=${
        this.data.city
      }`,
    });
  },

  toShopMap() {
    wx.navigateTo({
      url: `/pages/shop-map/shop-map?roomsList=${JSON.stringify(this.data.roomsList)}&city=${this.data.city}`,
    });
  },

  async loadRoomsList(fresh = false) {
    if (fresh) {
      wx.pageScrollTo({
        scrollTop: 0,
      });
    }
    const goodListPagination = this.goodListPagination || {
      index: 0,
      num: 20,
    };
    const privateData = this.privateData || {
      tabIndex: 0,
    };
    this.setData({
      roomsListLoadStatus: 1,
    });
    const pageSize = goodListPagination.num;
    let pageIndex = privateData.tabIndex * pageSize + goodListPagination.index + 1;
    if (fresh) {
      pageIndex = 0;
    }

    try {
      axios.get('/app/getAdList').then((res) => {
        const imgSrcs = res.data.banners?.map((item) => item.url) || [];
        this.setData({
          imgSrcs,
        });
      });
      const geo = {
        city: this.data.city,
        lat:this.data.lat,
        lng:this.data.lng
      }
      const nextList = await axios.get('/app/dpList', {
        current: pageIndex,
        pageSize: pageSize,
        ...geo,
      });
      let list = fresh ? nextList.data : this.data.roomsList.concat(nextList.data);
      try{
        list = list.map(item=>{
          const imgs = imgFormat(item.banners);
          item.tags = item.tags.split(",");
          if (item.distance < 1000) {
            item.distance += 'm'
          } else {
            item.distance = (item.distance / 1000).toFixed(1) + 'km'
          }
          item.bgImg = imgs[0]?.url || "https://ouyujingcheng.com/uploads/other/1709191919728_d5f9b3a8edd6145360de7bba120d2d4a_.jpg"
          return item;
        })
      }catch(err){
        console.log(err)
      }
      this.setData({
        roomsList: list,
        roomsListLoadStatus: 0,
      });
      this.goodListPagination.index = pageIndex;
      this.goodListPagination.num = pageSize;
    } catch (err) {
      this.setData({
        roomsListLoadStatus: 3,
      });
    } finally {
      this.setData({
        enable: false
      });
      wx.hideLoading();
    }
  },
  checkLocationAuth() {
    wx.getSetting({
      success: (res) => {
        let authSetting = res.authSetting
        if (authSetting['scope.userLocation']) {
          // 已授权
          this.getCityList()
        } else if (authSetting['scope.userLocation'] === false) {
          wx.showModal({
            title: '您未开启地理位置授权',
            content: '请在系统设置中打开位置授权，以便我们为您提供更好的服务',
            success: (res) => {
              if (res.confirm) {
                wx.openSetting()
              }
            }
          })
        } else {
          wx.authorize({
            scope: 'scope.userLocation',
            success: () => {
              this.getCityList()
            },
            fail: () => {
              wx.showModal({
                title: '您未开启地理位置授权',
                content: '请在系统设置中打开位置授权，以便我们为您提供更好的服务',
                success: (res) => {
                  if (res.confirm) {
                    wx.openSetting()
                  }
                }
              })
            }
          })
        }
      }
    })
  }
});